package com.chushouya.manager.dao.repository;


import com.general.framework.core.enums.DelFlagEnum;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Strings;
import com.general.framework.data.mybatis.BaseRepository;
import com.chushouya.manager.dao.entity.DeptEntity;
import com.chushouya.manager.dao.mapper.DeptMapper;
import com.chushouya.manager.dto.admin.dept.DeptListQuery;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

@Repository
public class DeptRepository extends BaseRepository<DeptMapper, DeptEntity, Long> {


    public List<DeptEntity> selectDeptList(DeptListQuery query) {
        Example example = buildQueryExample(query);
        example.orderBy("orderNum").asc();
        return this.selectByExample(example);
    }

    private Example buildQueryExample(DeptListQuery query) {
        Example example = this.buildExample();
        if (Strings.isNotEmpty(query.getDeptName())) {
            example.and().andLike("deptName", "%" + query.getDeptName() + "%");
        }
        if (Objects.nonNull(query.getStatus())) {
            example.and().andEqualTo("status", query.getStatus());
        }
        if (Lists.isNotEmpty(query.getDeptIdList())) {
            example.and().andIn("deptId", query.getDeptIdList());
        }
        example.and().andEqualTo("delFlag", DelFlagEnum.normal.getValue());
        return example;
    }

    public DeptEntity selectOneRole(DeptListQuery query) {
        Example example = this.buildExample();
        Example.Criteria c = example.createCriteria();
        if (Strings.isNotEmpty(query.getDeptName())) {
            c.andEqualTo("deptName", query.getDeptName());
        }
        if (Objects.nonNull(query.getIdNotEqualTo())) {
            c.andNotEqualTo("deptId", query.getIdNotEqualTo());
        }
        c.andEqualTo("delFlag", 0);
        return this.selectFirstOneByExample(example);
    }

    public int selectChildDeptCount(Long deptId) {
        Example example = this.buildExample();
        example.and().andEqualTo("parentId", deptId).andEqualTo("delFlag", 0);
        return this.selectCountByExample(example);
    }

    public List<DeptEntity> selectChildDeptList(Long deptId) {
        return this.mapper.selectChildDeptList(deptId);
    }

    public Long selectIdByName(String name) {
        Example example = buildExample();
        example.and().andEqualTo("deptName", name).andEqualTo("delFlag", 0);
        DeptEntity entity = selectFirstOneByExample(example);
        return entity == null ? null : entity.getDeptId();
    }

}
